import re

import sseclient
import requests
import json
import session

bot_app_key = "GKFleIcPwelfdAOedftFQfbNswbBfgNnivbJrlbQUkicXNIJeHMNCDoqnCTTwHacqqkxDkeUFGKOxFXkFTGiUNoCBIrKYNnLoklakAskjkZLajXCKyNGgcPdMuARODOT"  # 机器人密钥，不是BotBizId (从运营接口人处获取)
visitor_biz_id = "202403130001"  # 访客 ID（外部系统提供，需确认不同的访客使用不同的 ID）
streaming_throttle = 1  # 节流控制


def sse_client(sid: str):
    req_data = {
        "content": "",
        "bot_app_key": bot_app_key,
        "visitor_biz_id": visitor_biz_id,
        "session_id": sid,
        "streaming_throttle": streaming_throttle,
        'search_network': 'enable',
    }

    with open('样例.md', 'r', encoding='utf-8')as f:
        cleaned_content = []  # 存储处理后的每一行
        for line in f:
            if not re.search(r'!\[img\]\(.*?\)', line):
                cleaned_content.append(line)
        html = ''.join(cleaned_content)

    prompt = f"""请根据已提供的提示词使用指令跟随回答意图结合联网搜索分析下面文章，且按照提示词的要求返回json格式\n{html}"""
    req_data['content'] = prompt
    resp = requests.post("https://wss.lke.cloud.tencent.com/v1/qbot/chat/sse", data=json.dumps(req_data),
                         stream=True, headers={"Accept": "text/event-stream"})
    client = sseclient.SSEClient(resp)
    data = {}
    for ev in client.events():
        data = json.loads(ev.data)
        print(data)
    print(data['payload']['content'][8: -4])
    content = data['payload']['content'][8:].split('```')[0]
    result = json.loads(content)
    with open('result.json', 'w', encoding='utf-8') as f:
        json.dump(result, f, ensure_ascii=False, indent=2)


if __name__ == "__main__":
    session_id = session.get_session()
    sse_client(session_id)
